package org.gjy.m8.tool;

import com.jd.platform.async.callback.ICallback;
import com.jd.platform.async.callback.IWorker;
import com.jd.platform.async.executor.Async;
import com.jd.platform.async.worker.WorkResult;
import com.jd.platform.async.wrapper.WorkerWrapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-09-07 11:37:59
 */
public class AsyncToolTest {
    private static final Logger log = LoggerFactory.getLogger(AsyncToolTest.class);

    @Test
    public void test1() throws ExecutionException, InterruptedException {
        DeWork w = new DeWork();
        WorkerWrapper<String, User> workerWrapper = new WorkerWrapper.Builder<String, User>()
                .worker(w)
                .param("param11--2")
                .id("first")
                .callback(w)
                .build();
        Async.beginWork(1000, workerWrapper);
        log.info("workerWrapper.getWorkResult() {}", workerWrapper.getWorkResult());
        Async.shutDown();
    }

    private static final class DeWork implements IWorker<String, User>, ICallback<String, User> {

        @Override
        public void result(boolean b, String s, WorkResult<User> workResult) {
            try {
                TimeUnit.SECONDS.sleep(2);
                log.info("result {},{},{}", b, s, workResult.getResult());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void begin() {
            log.info("begin");
        }

        @Override
        public User action(String s, Map<String, WorkerWrapper> map) {
            try {
                TimeUnit.SECONDS.sleep(1);
                log.info("action s={},map={}", s, map);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return new User("user0");
        }

        @Override
        public User defaultValue() {
            User user = new User("default");
            log.info("defaultValue user: {}", user);
            return user;
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private static final class User {
        private String name;
    }

}
